<template>
  <div>
    <Header></Header>
    <div class="edit-container">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="form.title"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="摘要" prop="description">
          <el-input
            type="textarea"
            maxlength="200"
            show-word-limit
            rows="3"
            v-model="form.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <mavon-editor v-model="form.content"></mavon-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">发表博客</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// 新建和重新编辑是同一个页面所以需要有一个id
import Header from "../components/Header";
export default {
  name: "BlogEdit",
  components: { Header },
  data() {
    return {
      form: {
        id: "",
        title: "",
        description: "",
        content: "",
      },
    };
  },
  methods: {
    onSubmit() {
      const _this = this;
      //headers是config
      this.$axios
        .post("/blog/edit", _this.form, {
          headers: {
            "Authorization": localStorage.getItem("token"),
          },
        })
        .then((res) => {
          console.log(res);
          this.$confirm("将发布这篇文章, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                type: "success",
                message: "发布成功!",
              });
              this.$router.push("/blogs");
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消发布",
              });
            });
          //延迟跳转
          // clearTimeout(this.timer)
          // this.timer=setTimeout(() => {
          //   this.$router.push("/blogs");
          // }, 2500);
        });
    },
  },
  created() {
    //blogid可以通过路径的params来获取
    const _this = this;
    const blogId = this.$route.params.blogId;
    console.log(blogId);
    if (blogId) {
      //alert(localStorage.getItem("token"));
      this.$axios
        .get("/blog/" + blogId, {
          "Authorization": localStorage.getItem("token"),
        })
        .then((res) => {
          const blog = res.data.data;
          _this.form.id = blog.id;
          _this.form.title = blog.title;
          _this.form.description = blog.description;
          _this.form.content = blog.content;
        });
    }
  },
};
</script>
<style>
.edit-container {
  max-width: 60%;
  padding: 40px;
  padding-right: 60px;
  margin: auto;
}
</style>